/*
 * @Author Malred · Wang
 * @Date 2025-06-23 16:49:50
 * @Description 
 * @Path src/components/router-guard.jsx
 */
import {matchPath, Route, Routes, useLocation, useNavigate, useRoutes} from "react-router-dom";
import {Suspense, useEffect} from "react";
import routes from "~react-pages";
import Login from "../pages/login.jsx";
import NotFount from "../pages/not-fount.jsx";

const isAuthenticated = () => {
    return localStorage.getItem("token") !== null; // 示例逻辑
};

// 全局路由组件
function RouterGuard() {
    const navigate = useNavigate();
    const location = useLocation();

    // 添加 requiresAuth 属性
    const toNeedAuth = (r) => {
        const route = {...r, requiresAuth: true};
        if (route.children) {
            route.children = route.children.map(c => toNeedAuth(c));
        }
        return route;
    }
    const authRoutes = routes.map(toNeedAuth)

    useEffect(() => {
        /*
        // 无法匹配嵌套的路由
        const currentRoute = authRoutes.find(route =>
            matchPath({path: route.path, end: true}, location.pathname)
        );
        console.log(currentRoute)
        */
        console.log(location.pathname)

        // 全局导航守卫逻辑
        /*
        if (currentRoute?.requiresAuth && !isAuthenticated()) {
            navigate("/login", {replace: true});
        }
        */
        // 后续添加更多不需要身份验证的页面
        if (location.pathname !== '/login' && !isAuthenticated()) {
            navigate("/login", {replace: true});
        }
    }, [location, navigate]); // 监听路由变化

    return (
        <Suspense fallback={<p>Loading...</p>}>
            {useRoutes(
                [
                    ...authRoutes,
                    {
                        path: 'login',
                        element: <Login/>
                    },
                    {
                        path: "*",
                        element: <NotFount/>
                    }
                ]
            )}
        </Suspense>
    );
}

export default RouterGuard;